package com.xxgg.start.controller.system;


import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxgg.common.annotation.OpenLog;
import com.xxgg.common.enums.BusinessType;
import com.xxgg.common.exception.ApiException;
import com.xxgg.common.result.ResultJSON;
import com.xxgg.common.utils.poi.ExcelUtil;
import com.xxgg.system.model.po.User;
import com.xxgg.system.model.vo.UserRoleVo;
import com.xxgg.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 先谢郭嘉
 * @since 2023-01-31 04:33:30
 */
@Slf4j
@Api(tags = "用户管理")
@RestController
@RequestMapping("/system/user")
public class UserController {

    @Resource
    UserService userService;

    @ApiOperation(value = "获取用户和角色信息", httpMethod = "GET")
    @ApiImplicitParam(value = "用户id",name = "userId",required = true)
    @GetMapping("/getUserRole")
    public ResultJSON<UserRoleVo> getUserRole(String userId) {
        return ResultJSON.success(userService.getUserRole(userId));
    }

    @ApiOperation(value = "判断用户名是否存在", httpMethod = "GET")
    @ApiImplicitParam(value = "用户名",name = "userName",required = true)
    @GetMapping("/isUserName")
    public ResultJSON<Boolean> isUserName(String userName) {
        return userService.isUserName(userName) ? ResultJSON.success() : ResultJSON.error();
    }

    @SaCheckPermission("user:add")
    @OpenLog(module = "用户管理", name = "新增用户", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增用户",httpMethod = "POST")
    @ApiImplicitParam(value = "用户实体",name = "user",required = true)
    @PostMapping("/add")
    public ResultJSON<Boolean> addUser(@RequestBody @Validated User user) throws ApiException {
        return userService.addUser(user) ? ResultJSON.success() : ResultJSON.error();
    }

    @SaCheckPermission("user:page")
    @OpenLog(module = "用户管理", name = "分页查询用户列表", businessType = BusinessType.PAGE)
    @ApiOperation(value = "分页查询用户列表", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "每页数量",name = "size",required = true),
            @ApiImplicitParam(value = "页码",name = "current",required = true),
            @ApiImplicitParam(value = "启用状态（0启用，1停用，2冻结）",name = "isEnable",required = false),
            @ApiImplicitParam(value = "性别（1未知，2男，3女）",name = "gender",required = false),
            @ApiImplicitParam(value = "模糊查询条件",name = "search",required = false),
    })
    @GetMapping("/page")
    public ResultJSON<Page<User>> userPage(Integer size, Integer current, String isEnable, String gender, String search){
        Page<User> userPage = userService.lambdaQuery()
                .eq(StrUtil.isNotBlank(isEnable), User::getIsEnable, isEnable)
                .eq(StrUtil.isNotBlank(gender), User::getGender, gender)
                .and(StrUtil.isNotBlank(search), item -> item
                        .like(User::getUserName, search).or()
                        .like(User::getNickName, search).or()
                        .like(User::getPhone, search).or()
                        .like(User::getEmail, search))
                .orderByDesc(User::getUpdateTime)
                .page(new Page<>(current, size));
        return ResultJSON.success(userPage);
    }

    @SaCheckPermission("user:delete")
    @OpenLog(module = "用户管理", name = "删除用户（物理删除）", businessType = BusinessType.INSERT)
    @ApiOperation(value = "删除用户（物理删除）",httpMethod = "DELETE")
    @ApiImplicitParam(value = "用户id",name = "userId",required = true)
    @DeleteMapping("/delete")
    public ResultJSON<Boolean> deleteUser(String userId) {
        return userService.removeById(userId) ? ResultJSON.success() : ResultJSON.error();
    }

    @SaCheckPermission("user:update")
    @OpenLog(module = "用户管理", name = "编辑用户", businessType = BusinessType.INSERT)
    @ApiOperation(value = "编辑用户",httpMethod = "POST")
    @ApiImplicitParam(value = "用户实体",name = "user",required = true)
    @PostMapping("/update")
    public ResultJSON<Boolean> updateUser(@RequestBody @Validated User user) throws ApiException {
        return userService.updateUser(user) ? ResultJSON.success() : ResultJSON.error();
    }

    @SaCheckPermission("user:export")
    @OpenLog(module = "用户管理", name = "导出用户数据列表", businessType = BusinessType.EXPORT)
    @ApiOperation(value = "导出用户数据列表", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "导出的文件名称", name = "fileName", required = false),
            @ApiImplicitParam(value = "启用状态（0启用，1停用，2冻结）",name = "isEnable",required = false),
            @ApiImplicitParam(value = "性别（1未知，2男，3女）",name = "gender",required = false)
    })
    @GetMapping(value = "/export", produces = "application/octet-stream")
    public void export(String isEnable, String gender, String fileName, HttpServletResponse response) {
        List<User> userList = userService.lambdaQuery()
                .eq(StrUtil.isNotBlank(isEnable), User::getIsEnable, isEnable)
                .eq(StrUtil.isNotBlank(gender), User::getGender, gender)
                .list();
        if(StringUtils.isEmpty(fileName)) fileName = "用户数据列表";
        ExcelUtil.exportExcel(userList, fileName, User.class, response);
    }


}
